'use strict'
const EventEmitter = require('events')
const Client = require('../client')
const RoomHttp = require('../roomhttp')
class PandaRoom extends EventEmitter {
  constructor (roomId) {
    super()
    this.roomId = roomId
    this.rid = 'rid'
    this.appid = 'appId'
    this.ts = 'ts'
    this.sign = ''
    this.authtype = ''
    this.count = 0
    this.k = '1'
    this.t = '300'
    this.info = {}
    this.gifts = {}
    this.count = 0
    this.fans = 0
    this.isInit = false
    this.http = new RoomHttp()
    this._getGift()
  }
  _getInfo () {
    this.http.on('info', this.onInfo.bind(this))
    this.http.get({
      hostname: 'www.panda.tv',
      port: 80,
      path: `/api_room_v2?roomid=${this.roomId}&pub_key=&__plat=pc_web&_=${new Date().getTime()}`,
      method: 'GET',
      headers: {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'
      }
    })
  }
  onInfo (info) {
    if (info && info.errno === 0) {
      let data = info.data
      let obj = {
        data: {
          avatar: data.hostinfo.avatar,
          room_name: data.roominfo.name,
          room_id: data.roominfo.id,
          owner_name: data.hostinfo.name,
          online: data.roominfo.person_num,
          owner_weight: '0',
          fans_num: this.fans,
          room_status: data.roominfo.status === '2' ? '1' : '2',
          gift: [{
            id: '1',
            pc: '1',
            type: '1',
            name: '竹子'
          }]
        },
        error: 0
      }
      for (let i = 0; i < this.gifts.length; i++) {
        obj.data.gift.push({
          id: this.gifts[i].id,
          pc: this.gifts[i].price,
          type: '2',
          name: this.gifts[i].name
        })
      }
      this.info = obj
      if (!this.isInit) {
        this.emit('init', this.info)
        this.login()
        this.isInit = true
      } else {
        this.emit('update', this.info)
      }
    } else {
      if (!this.isInit) {
        this.emit('init', null)
      }
    }
  }
  _getGift () {
    let http = new RoomHttp()
    http.on('error', () => {
      this.emit('init', null)
    })
    http.on('info', (info) => {
      if (!info || info.errno !== 0) {
        this.emit('init', null)
        return
      }
      this.gifts = info.data.items
      this._getFans()
    })
    http.get({
      hostname: 'mall.panda.tv',
      port: 80,
      path: `/ajax_gift_gifts_get?roomid=${this.roomId}&__plat=pc_web`,
      method: 'GET',
      headers: {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'
      }
    })
  }
  _getFans () {
    // http://www.panda.tv/room_followinfo?roomid=392616&_=1474186210811
    let http = new RoomHttp()
    http.on('error', () => {
      this.emit('init', null)
    })
    http.on('info', (info) => {
      if (!info || info.errno !== 0) {
        this.emit('init', null)
        return
      }
      this.fans = info.data.fans
      this._getInfo()
    })
    http.get({
      hostname: 'www.panda.tv',
      port: 80,
      path: `/room_followinfo?roomid=${this.roomId}&_=${new Date().getTime()}`,
      method: 'GET',
      headers: {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'
      }
    })
  }
  login () {
    let http = new RoomHttp()
    http.on('error', () => {
      this.emit('error')
    })
    http.on('info', (info) => {
      if (!info || info.errno !== 0) {
        this.emit('error')
        return
      }
      if (info.data.appid) {
        let addr = info.data.chat_addr_list[0].split(':')
        let ip = addr[0]
        let port = addr[1]
        this.rid = info.data.rid
        this.appid = info.data.appid
        this.ts = info.data.ts
        this.sign = info.data.sign
        this.authtype = info.data.authType
        this.client = new Client(port, ip, 60 * 1000, () => {
          let buf = new Buffer([0x00, 0x06, 0x00, 0x00])
          this.client.send(buf)
          this._getInfo()
        })
        this.client.on('onConnect', this.onConnect.bind(this))
        this.client.on('onData', this.onData.bind(this))
        this.client.start()
      } else {
        let rid = info.data.rid
        let roomid = info.data.roomid
        let sign = info.data.sign
        let ts = info.data.ts
        http.get({
          hostname: 'api.homer.panda.tv',
          port: 80,
          path: `/chatroom/getinfo?rid=${rid}&roomid=${roomid}&retry=0&sign=${sign}&ts=${ts}&_=${new Date().getTime()}`,
          method: 'GET',
          headers: {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'
          }
        })
      }
    })
    http.get({
      hostname: 'www.panda.tv',
      port: 80,
      path: `/ajax_chatroom?roomid=${this.roomId}&_=${new Date().getTime()}`,
      method: 'GET',
      headers: {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'
      }
    })
  }
  onConnect () {
    let msg = `u:${this.rid}@${this.appid}\nk:${this.k}\nt:${this.t}\nts:${this.ts}\nsign:${this.sign}\nauthtype:${this.authtype}`
    let buf = new Buffer(0)
    let buf1 = new Buffer([0x00, 0x06, 0x00, 0x02])
    let buf2 = new Buffer(2)
    buf2.writeUInt16BE(msg.length)
    let buf3 = new Buffer(msg)
    let buf4 = new Buffer([0x00, 0x06, 0x00, 0x00])
    buf = Buffer.concat([buf1, buf2, buf3, buf4], buf1.length + buf2.length + buf3.length + buf4.length)
    this.client.send(buf)
  }
  onData (data) {
    if (data.indexOf('00060006') !== 0 && data.indexOf('00060001') !== 0) {
      try {
        let buffer = new Buffer(data.length / 2)
        let index = 0
        for (var i = 0; i < data.length / 2; i++) {
          buffer[i] = parseInt('0x' + data[index] + data[index + 1], 16)
          index += 2
        }
        // |---11位--|--总弹幕length(4位)--|--12位分隔符--|--单条弹幕length(4位)--|--(弹幕信息)--|
        let total = buffer.readUInt32BE(11)
        let readLength = 0
        let readCount = 11 + 4
        do {
          readCount += 12
          let length = buffer.readUInt32BE(readCount)
          readLength += length
          readCount += 4
          let body = buffer.toString('utf8', readCount, readCount + length)
          let obj = JSON.parse(body)
          if (obj.data.to.toroom === this.roomId && obj.data.from.rid !== '-1') {
            this.emit('data', this.convert(obj))
          }
          readCount += length
        } while (total > readLength + 64)
      } catch (e) {
        this.emit('dataError')
      }
    }
  }
  convert (info) {
    console.log(info)
    let msg = {}
    var date = new Date()
    let data = info.data
    let from = data.from
    let type = info.type
    switch (type) {
      case '1':
        msg.type = 'chatmsg'
        msg.txt = data.content
        break
      case '206':
        msg.type = 'dgb'
        msg.gfid = '1'
        msg.count = data.content
        break
      case '306':
        msg.type = 'dgb'
        msg.gfid = data.content.id
        break
    }
    msg.uid = from.rid
    msg.level = from.level || '0'
    msg.nn = from.nickName
    msg.rid = data.to.toroom
    msg.serverdate = date.getHours() + ':' + date.getMinutes()
    return msg
  }
  destroy () {
    this.client.close()
  }
}
module.exports = PandaRoom
